import router from "./router";
import Nprogress, { done } from "nprogress";
import "nprogress/nprogress.css";
import store from "./store";
import { asyncRoutes } from "@/router";

const whileList = ["/login", "/404"];

router.beforeEach(async (to, from, next) => {
  Nprogress.start();
  if (store.getters.token) {
    if (to.path === "/login") {
      next("/");
      Nprogress.done();
    } else {
      if (!store.getters.name) {
        // TODO 获取资料
        const {
          roles: { menus },
        } = await store.dispatch("user/getInfo");
        const filterRoutes = asyncRoutes.filter((item) => {
          return menus.includes(item.name);
        });
        // 筛选后的路由
        store.commit('user/setRoutes', filterRoutes)
        console.log("filterRoutes", filterRoutes);
        router.addRoutes([
          ...filterRoutes,
          { path: "*", redirect: "/404", hidden: true },
        ]); // 添加动态路由信息到路由表 404页面应该放到最后
        // router添加动态路由之后，需要转发一下
        next(to.path); // 目的是让路由拥有信息 router的已知缺陷
      }
      next();
    }
  } else {
    if (whileList.indexOf(to.path) > -1) {
      next();
    } else {
      next("/login");
      Nprogress.done();
    }
  }
});

router.afterEach(() => {
  Nprogress.done();
});
